"use strict";

!function () {
	// 索引和标志
	var itemIndex = 0;
	var flag2 = 0;
	var flag = 0;
	// 判断有没有这个类
	function hasClass(el, className) {
		if (el && el.className !== void 0) {
			var classList = el.className.split(/\s+/);
			if (classList.indexOf(className) >= 0) {
				return true;
			} else return false;
		} else {
			return false;
		}
	}

	//取得css样式
	function getStyle(element, attr) {
		return element.currentStyle ? element.currentStyle[attr] : window.getComputedStyle(element, null)[attr] || 0;
	}

	// 对dot绑定点击事件。清空所有active，然后对特定的绑定active
	function bindDot() {
		var tagDot = document.getElementsByClassName("dot-container")[0];
		tagDot.addEventListener("click", function (e) {
			if (flag2) {
				clearTimeout(flag2);
			}
			var target = e.target;
			if (hasClass(target, "dot")) {
				if (itemIndex === target.dataset.index) {
					return;
				} else {
					itemIndex = target.dataset.index;
					var tagpos = -itemIndex * 600;
					moveTo(tagpos);
				}
			} else {
				return;
			}
		});
	}

	// 对前后按钮绑定点击事件
	function bindBottom() {
		var buttonParent = document.getElementsByClassName("button")[0];
		buttonParent.addEventListener("click", function (e) {
			if (flag2) {
				clearTimeout(flag2);
			}
			var target = e.target;
			if (target.className === "up") {
				if (flag === 0) {
					cutItermIndex();
				} else {
					cutItermIndex();
					cutItermIndex();
					flag = 0;
				}
				// cutItermIndex();
			} else if (target.className === "down") {
				if (flag === 0) {
					addItermIndex();
				} else {
					flag = 0;
				}
			} else {
				return;
			}
			var tagpos = -itemIndex * 600;
			moveTo(tagpos);
		});
	}

	// 鼠标暂停
	function mousehover() {
		var tag = document.getElementsByClassName("container")[0];
		tag.addEventListener("mouseenter", function () {
			flag = 1;
			if (flag2) {
				clearTimeout(flag2);
			}
		});
		tag.addEventListener("mouseleave", function () {
			flag = 0;
			run();
		});
	}

	// 绑定函数
	function bindEvent() {
		bindDot();
		bindBottom();
		mousehover();
	}

	// 执行绑定事件
	bindEvent();

	// 运动函数
	function moveTo(endPos) {
		// console.log("moveto");
		var element = document.getElementsByClassName("contain")[0];
		if (element.move) {
			clearTimeout(element.move);
			// element.style.left = endPos + 'px';
		}
		var startPos = parseInt(getStyle(element, "left"));
		if (startPos === endPos) {
			return true;
		}
		if (startPos < endPos) {
			startPos += 10;
		}
		if (startPos > endPos) {
			startPos -= 10;
		}
		element.style.left = startPos + 'px';
		element.move = setTimeout(function () {
			moveTo(endPos);
		}, 1);
	}

	function addItermIndex() {
		itemIndex++;
		if (itemIndex > 4) {
			itemIndex = 0;
		}
	}

	function cutItermIndex() {
		itemIndex--;
		if (itemIndex < 0) {
			itemIndex = 4;
		}
	}

	// 运动
	function run() {
		var tagpos = -itemIndex * 600;
		moveTo(tagpos);
		addItermIndex();
		flag2 = setTimeout(run, 3000);
	}
	// 执行
	run();
}();